package com.apanal.qlife.sys.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.apanal.qlife.common.constants.Constants;
import com.apanal.qlife.common.page.Page;
import com.apanal.qlife.common.page.PageReturn;
import com.apanal.qlife.common.util.IdWorkerFactory;
import com.apanal.qlife.sys.dao.RoleMapper;
import com.apanal.qlife.sys.dao.RoleResourceRelMapper;
import com.apanal.qlife.sys.model.Role;
import com.apanal.qlife.sys.model.RoleResourceRel;
import com.apanal.qlife.sys.model.User;
import com.apanal.qlife.sys.service.ResourceService;
import com.apanal.qlife.sys.service.RoleService;

/**
 * 角色服务层接口实现类
 * 
 * @author shuliangxing
 * 
 * @date 2015-1-14上午11:36:08
 */
@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	RoleMapper mapper;

	@Autowired
	RoleResourceRelMapper roleResourceRelMapper;

	@Autowired
	ResourceService resourceService;

	@Override
	public String deleteById(Long id) {
		mapper.deleteByPrimaryKey(id);
		// 删除所有旧关联数据
		roleResourceRelMapper.deletesByRolId(id);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public String insert(Role record) {
		record.setRolId(IdWorkerFactory.nextId());
		mapper.insert(record);

		// 如果资源id字符串不为空,则新增角色资源关联表数据
		if (record.getResourceIds() != null
				&& !"".equals(record.getResourceIds())) {
			String[] idArray = record.getResourceIds().split(",");
			List<RoleResourceRel> list = new ArrayList<RoleResourceRel>();
			for (String resId : idArray) {
				RoleResourceRel rel = new RoleResourceRel();
				rel.setRelId(IdWorkerFactory.nextId());
				rel.setRolId(record.getRolId());
				rel.setResId(Long.valueOf(resId));
				rel.setInsertBy(record.getInsertBy());
				list.add(rel);
			}
			if (!list.isEmpty()) {
				roleResourceRelMapper.inserts(list);
			}
		}
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public String insertSelective(Role record) {
		mapper.insertSelective(record);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public Role selectById(Long id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public String updateByIdSelective(Role record) {
		mapper.updateByPrimaryKeySelective(record);
		// 删除所有旧关联数据
		roleResourceRelMapper.deletesByRolId(record.getRolId());

		if (record.getResourceIds() != null
				&& !"".equals(record.getResourceIds())) {
			// 新增关联数据
			String[] idArray = record.getResourceIds().split(",");
			List<RoleResourceRel> list = new ArrayList<RoleResourceRel>();
			for (String resId : idArray) {
				RoleResourceRel rel = new RoleResourceRel();
				rel.setRelId(IdWorkerFactory.nextId());
				rel.setRolId(record.getRolId());
				rel.setResId(Long.valueOf(resId));
				rel.setInsertBy(record.getLastUpdateBy());
				list.add(rel);
			}
			if (!list.isEmpty()) {
				roleResourceRelMapper.inserts(list);
			}
		}
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public String updateById(Role record) {
		mapper.updateByPrimaryKey(record);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public Role selectRelationById(Long id) {
		Role record = new Role();
		record.setRolId(id);
		Role role = mapper.selectRelation(record).get(0);
		// 倒序排列子集合,使顺序与列表页面、弹出选择页面顺序保持一致
		Collections.reverse(role.getResourceList());
		return role;
	}

	@Override
	public PageReturn<Role> selectRelationForPage(Role entity, Page page) {
		int count = mapper.selectRelationForPageCount(entity, page);
		List<Role> list = mapper.selectRelationForPage(entity, page);
		for (Role role : list) {
			role.setResourceList(resourceService.selectByRolId(role.getRolId()));
		}
		return new PageReturn<Role>(list, count, page, entity);
	}

	@Override
	public String softDelete(Long id, Long useId) {
		Role entity = new Role();
		entity.setRolId(id);
		entity.setLastUpdateBy(useId);
		entity.setStatus(Constants.IS_VALID_FALSE);
		mapper.updateByPrimaryKeySelective(entity);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public List<Role> selectAll() {
		return mapper.select(null);
	}

	@Override
	public String updateToEnableOrDisable(Role role) {
		role.setNormal(role.getNormal() == Constants.IS_VALID_TRUE ? Constants.IS_VALID_FALSE
				: Constants.IS_VALID_TRUE);
		mapper.updateByPrimaryKeySelective(role);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public Boolean checkRoleNameExist(Long rolId, String rolName) {
		Boolean result = false;
		Role role = new Role();
		role.setRolName(rolName);
		List<Role> list = mapper.select(role);

		// 角色id大于0,表示修改校验,排除当前角色
		if (rolId > 0) {
			for (Role r : list) {
				if (!r.getRolId().equals(rolId)) {
					result = true;
					break;
				}
			}
		}
		// 表示新增角色校验
		else {
			result = !list.isEmpty();
		}
		return result;
	}

	@Override
	public Set<String> findNamesByUser(User user) {
		return mapper.findNamesByUserName(user.getUseName());
	}

	@Override
	public String findNameStrByUser(User user) {
		RoleService proxyRoleService = (RoleService) AopContext.currentProxy();
		Object[] array = proxyRoleService.findNamesByUser(user).toArray();
		String name = "";
		for (int i = 0; i < array.length; i++) {
			if (i > 0) {
				// 中文逗号方便tips换行
				name += "，";
			}
			name += array[i];
		}
		return name;
	}

	@Override
	public List<Role> selectByUseId(Long useId) {
		return mapper.selectByUserId(useId);
	}

	@Override
	public List<Role> selectByGroId(Long groId) {
		return mapper.selectByGroId(groId);
	}

	@Override
	public List<Role> selectByIds(String ids) {
		if (ids == null || "".equals(ids)) {
			return null;
		} else {
			Role param = new Role();
			param.setRolIds(ids);
			return mapper.select(param);
		}
	}

	@Override
	public Role findRoleNameByid(Long useId) {

		return mapper.findRoleNameByid(useId);
	}

}
